//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useState } from "react";
import { observer } from 'mobx-react';
import type { DepartMentInfo, DepartMentOrMember } from "@/api/org";
import { remove_depart_ment, update_depart_ment, move_depart_ment } from "@/api/org";
import { Button, message, Modal, Space, Table } from "antd";
import { useStores } from "@/hooks";
import type { ColumnsType } from 'antd/lib/table';
import { EditText } from "@/components/EditCell/EditText";
import { request } from "@/utils/request";
import { report_error } from "@/api/client_cfg";
import SelectDepartMentModal from "./SelectDepartMentModal";

export interface DepartMentListProps {
    parentDepartMentId: string;
    onSelect: (newItem: DepartMentOrMember) => void;
}

const DepartMentList = (props: DepartMentListProps) => {
    const userStore = useStores('userStore');
    const orgStore = useStores('orgStore');

    const [moveDepartMentInfo, setMoveDepartMentInfo] = useState<DepartMentInfo | null>(null);
    const [removeDepartMentInfo, setRemoveDepartMentInfo] = useState<DepartMentInfo | null>(null);


    const moveDepartMent = async (destDepartMentId: string) => {
        if (moveDepartMentInfo == null) {
            return;
        }
        await request(move_depart_ment({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            depart_ment_id: moveDepartMentInfo.depart_ment_id,
            parent_depart_ment_id: destDepartMentId,
        }));
        await orgStore.onUpdateDepartMent(orgStore.curOrgId, moveDepartMentInfo.depart_ment_id);
        if (moveDepartMentInfo.parent_depart_ment_id != "") {
            await orgStore.onUpdateDepartMent(orgStore.curOrgId, moveDepartMentInfo.parent_depart_ment_id);
        }
        if (destDepartMentId != "") {
            await orgStore.onUpdateDepartMent(orgStore.curOrgId, destDepartMentId);
        }
        setMoveDepartMentInfo(null);
        message.info("移动成功");
    }

    const removeDepartMent = async () => {
        if (removeDepartMentInfo == null) {
            return;
        }
        await request(remove_depart_ment({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            depart_ment_id: removeDepartMentInfo.depart_ment_id,
        }));
        await orgStore.onRemoveDepartMent(orgStore.curOrgId, removeDepartMentInfo.depart_ment_id);
        if (removeDepartMentInfo.parent_depart_ment_id != "") {
            await orgStore.onRemoveDepartMent(orgStore.curOrgId, removeDepartMentInfo.parent_depart_ment_id);
        }
        setRemoveDepartMentInfo(null);
        message.info("删除成功");
    };

    const columns: ColumnsType<DepartMentInfo> = [
        {
            title: "名称",
            render: (_, row: DepartMentInfo) => (
                <EditText editable={userStore.userInfo.userId == orgStore.curOrg?.owner_user_id && row.depart_ment_id != orgStore.curOrg?.new_member_depart_ment_id}
                    content={row.depart_ment_name} showEditIcon
                    onChange={async (value) => {
                        if (value.trim() == "") {
                            return false;
                        }
                        try {
                            await request(update_depart_ment({
                                session_id: userStore.sessionId,
                                org_id: orgStore.curOrgId,
                                depart_ment_id: row.depart_ment_id,
                                depart_ment_name: value.trim(),
                            }));
                            await orgStore.onUpdateDepartMent(orgStore.curOrgId, row.depart_ment_id);
                            return true;
                        } catch (e) {
                            console.log(e);
                            report_error({
                                err_data: `${e}`,
                            });
                            return false;
                        }
                    }}
                    onClick={() => {
                        props.onSelect({
                            type: "departMent",
                            id: row.depart_ment_id,
                            value: row,
                        });
                    }}
                />
            ),
        },
        {
            title: "下级部门数量",
            dataIndex: "sub_depart_ment_count",
            width: 100,
        },
        {
            title: "下属成员数量",
            dataIndex: "sub_member_count",
            width: 100,
        },
        {
            title: "操作",
            width: 150,
            render: (_, row: DepartMentInfo) => (
                <Space size="large">
                    <Button type="link" disabled={!(userStore.userInfo.userId == orgStore.curOrg?.owner_user_id && row.depart_ment_id != orgStore.curOrg?.new_member_depart_ment_id)}
                        style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setMoveDepartMentInfo(row);
                        }}>移动</Button>
                    <Button type="link" disabled={!(userStore.userInfo.userId == orgStore.curOrg?.owner_user_id && row.depart_ment_id != orgStore.curOrg?.new_member_depart_ment_id && row.sub_depart_ment_count == 0 && row.sub_member_count == 0)}
                        style={{ minWidth: 0, padding: "0px 0px" }}
                        danger onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setRemoveDepartMentInfo(row);
                        }}>删除</Button>
                </Space>
            ),
        }
    ];

    return (
        <>
            <Table rowKey="depart_ment_id" dataSource={orgStore.departMentList.filter(item => item.parent_depart_ment_id == props.parentDepartMentId)}
                columns={columns} pagination={false} />
            {moveDepartMentInfo != null && (
                <SelectDepartMentModal skipDepartMentIdList={[moveDepartMentInfo.parent_depart_ment_id, moveDepartMentInfo.depart_ment_id, orgStore.curOrg?.new_member_depart_ment_id ?? ""]}
                    onCancel={() => setMoveDepartMentInfo(null)}
                    onOk={departMentId => moveDepartMent(departMentId)} />
            )}
            {
                removeDepartMentInfo != null && (
                    <Modal open title="删除部门" mask={false}
                        okText="删除" okButtonProps={{ danger: true }}
                        onCancel={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setRemoveDepartMentInfo(null);
                        }}
                        onOk={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            removeDepartMent();
                        }}>
                        是否删除部门&nbsp;{removeDepartMentInfo.depart_ment_name}&nbsp;?
                    </Modal>
                )
            }

        </>
    );
};

export default observer(DepartMentList);